<?php 
abstract class Dao {
	protected $_db, $_cache, $_solr;
	protected function __construct()
	{
		$this->_db = Yii::app()->db;
		$this->_db->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
		$this->_cache = Yii::app()->cache;
	}
		
	protected function args_merge($defaults, $args, $setNull = false){
		foreach($args as $key=>$value){
			if(!array_key_exists($key, $defaults)){
				unset($args[$key]);
			} else if($setNull && $value ==''){
				$args[$key] = null;
			}
		}
		return array_merge($defaults, $args);
	}
	
	protected function generateKeyCache($id, $args = null){
		if(is_array($args)){		
			foreach($args as $r){
				if(is_array($r)) $r = serialize($r); 
				$id .= '_'.$r;
			}
		} else $id .= '_'.$args;
		return md5($id);
	}
	
	protected function setMasterCache($strKey, $strMasterKey){
		try{
			$arrMasterCache = $this->_cache->get($strMasterKey);
			/*create master cache if not exist*/
			if($arrMasterCache === false){
				$arrMasterCache = array();
			}
			/*add key to master cache*/
			if(empty($arrMasterCache[$strKey]))
			{
				$arrMasterCache[$strKey] = $strKey;
				return $this->_cache->set($strMasterKey, $arrMasterCache, 2592000); //store master in 30 days
			}
			return false;
		} catch(Exception $e){
			throw new Exception($e->getMessage().': '.$strKey.' : '.$strMasterKey);
		}
	}
	
	protected function clearMasterCache($strMasterKey){
		try{
			$arrMasterCache = $this->_cache->get($strMasterKey);
			if($arrMasterCache !== false){
				foreach($arrMasterCache as $key){
					$this->_cache->delete($key);
				}
				return $this->_cache->delete($strMasterKey);
			}	
			return false;
		} catch(Exception $e){
			throw new Exception($e->getMessage().': '.$strMasterKey);
		}
	}
}